package io.github.hadyang.leetcode;

import com.google.common.base.Splitter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author haoyang.shi
 * @date 2020-01-31
 */
public class ArrayCodeC {
  private static final Pattern ARRAY_STR_INT_PATTERN =
      Pattern.compile("\\[(\\s*-?\\d+,?\\s*)+]", Pattern.MULTILINE);

  private static final Pattern ARRAY_STR_CHAR_PATTERN =
      Pattern.compile("\\[(\\s*'.',?)+]", Pattern.MULTILINE);

  public static int[] deserializeInt(String data) {
    String numsStr = data.replaceAll("\\[", "").replaceAll("]", "");
    List<String> splited = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(numsStr);

    int[] res = new int[splited.size()];
    int i = 0;
    for (String numStr : splited) {
      res[i++] = Integer.parseInt(numStr, 10);
    }

    return res;
  }

  public static char[] deserializeChar(String data) {
    String numsStr = data.replaceAll("\\[", "").replaceAll("]", "");
    List<String> splited = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(numsStr);

    char[] res = new char[splited.size()];
    int i = 0;
    for (String str : splited) {
      res[i++] = str.charAt(1);
    }

    return res;
  }

  public static int[][] deserializeGraphInt(String data) {
    List<int[]> resList = new ArrayList<>();

    Matcher matcher = ARRAY_STR_INT_PATTERN.matcher(data);
    while (matcher.find()) {
      resList.add(deserializeInt(matcher.group(0)));
    }

    if (resList.isEmpty()) return new int[0][0];

    int[][] res = new int[resList.size()][resList.get(0).length];
    for (int i = 0; i < resList.size(); i++) {
      res[i] = resList.get(i);
    }

    return res;
  }

  public static char[][] deserializeGraphChar(String data) {
    List<char[]> resList = new ArrayList<>();

    Matcher matcher = ARRAY_STR_CHAR_PATTERN.matcher(data);
    while (matcher.find()) {
      resList.add(deserializeChar(matcher.group(0)));
    }

    if (resList.isEmpty()) return new char[0][0];

    char[][] res = new char[resList.size()][resList.get(0).length];
    for (int i = 0; i < resList.size(); i++) {
      res[i] = resList.get(i);
    }

    return res;
  }
}
